package top.yxf.spring.beans.factory.support;

import top.yxf.spring.BeansException;
import top.yxf.spring.beans.factory.BeanFactory;
import top.yxf.spring.beans.factory.config.BeanDefinition;

/**
 * @author xs.wu
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {


    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    protected <T> T doGetBean(String beanName, Object ... args) {
        // 先获取单例
        Object bean = getSingleton(beanName);
        if (bean != null) {
            return (T) bean;
        }
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        return (T) createBean(beanName, beanDefinition, args);
    }

    /**
     * 获取BeanDefinition对象
     * @param beanName
     * @return
     * @throws BeansException
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * 创建bean
     * @param beanName bean 名称
     * @param beanDefinition bean中的一些核心属性 如(beanClass、scope、isLazy、dependsOn、primary、initMethodName）
     * @return
     * @throws BeansException
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;
}
